package com.wolfheader.wolfgame.weixin;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import com.wolfheader.wolfgame.util.HttpClientUtil;

import net.sf.json.JSONObject;

public class WeiXinUtils {
	public static final String appid = "wxf03432cd145651e6";

	public static final String appsecret = "d5da3da3d40578ece61e23a82aa6cabf";

	public static String jsapi_ticket;

	public static String access_token;

	public static Integer jsapi_time;

	public static Integer access_time;

	public static boolean isStart = false;

	public static void init() {
		startWeixinTimer();
	}
	
	public static void updateWeixinConfig(){
		getAccessToken();
		getApiTiket();
	}

	public static void getAccessToken() {
		String accessUrl = "https://api.weixin.qq.com/cgi-bin/token";
		String accessParam = "grant_type=client_credential&appid=APPID&secret=APPSECRET";
		String result = HttpClientUtil.sendGet(accessUrl,
				accessParam.replace("APPID", appid).replace("APPSECRET", appsecret));
		JSONObject json = JSONObject.fromObject(result);
		WeixinAccessTokenBean bean = (WeixinAccessTokenBean) JSONObject.toBean(json, WeixinAccessTokenBean.class);
		access_token = bean.getAccess_token(); 
	}

	public static void getApiTiket() {
		String url = "http://api.weixin.qq.com/cgi-bin/ticket/getticket";
		String param = "type=jsapi&access_token=ACCESS_TOKEN";
		String result = HttpClientUtil.sendGet(url, param.replace("ACCESS_TOKEN", access_token));
		JSONObject json = JSONObject.fromObject(result);
		WeixinTikectBean bean = (WeixinTikectBean) JSONObject.toBean(json, WeixinTikectBean.class);
		jsapi_ticket = bean.getTicket();
	}
	
	public static void startWeixinTimer() {
		if(isStart){
			return;
		}
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				System.out.println("updateWeixinConfig");
				updateWeixinConfig();
			}
		}, 0 , 600000);
	}

	public static WeixinSignElem sign(String url) {
		String nonce_str = create_nonce_str();
		String timestamp = create_timestamp();
		String string1;
		String signature = "";

		// 注意这里参数名必须全部小写，且必须有序
		string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
		System.out.println(string1);

		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(string1.getBytes("UTF-8"));
			signature = byteToHex(crypt.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		WeixinSignElem elem = new WeixinSignElem();
		elem.setAppId(appid);
		elem.setJsapi_ticket(jsapi_ticket);
		elem.setSignature(signature);
		elem.setTimestamp(timestamp);
		elem.setNonceStr(nonce_str);
		return elem;
	}

	private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}

	private static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}

	private static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}

}